package com.miyake.dsp.otdr;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.miyake.dsp.ComplexArray;
import com.miyake.dsp.ScilabExecute;

public class Fiber {
	private String name;
	private List<FiberProperties> props;
	
	public Fiber(String name) {
		this.name = name;
		props = new ArrayList<FiberProperties>();
	}
	
	public FiberProperties getProperties(double wavelength) {
		String command = "d=splin(data1, data2);xx=linspace(650,1650,1001);ret=interp(xx, data1, data2, d);";
		double wave[] = new double[props.size()];
		double ior[] = new double[props.size()];
		double linBsc[] = new double[props.size()];
		double linAtt[] = new double[props.size()];
		
		int i = 0;
		for (FiberProperties f : props) {
			wave[i] = f.getWavelength();
			ior[i] = f.getIor();
			linBsc[i] = f.getLinBsc();
			linAtt[i] = f.getLinAttenuation();
			i++;
		}
		ComplexArray retIOR = ScilabExecute.execute(command, new ComplexArray(wave), new ComplexArray(ior), "ret");
		ComplexArray retBSC = ScilabExecute.execute(command, new ComplexArray(wave), new ComplexArray(linBsc), "ret");
		ComplexArray retAtt = ScilabExecute.execute(command, new ComplexArray(wave), new ComplexArray(linAtt), "ret");

		int c = (int)(wavelength - 650);
		
//		LineChartPanel.showChart(retIOR.getRealPart(), "ior");
//		LineChartPanel.showChart(retBSC.getRealPart(), "bsc");
//		LineChartPanel.showChart(retAtt.getRealPart(), "att");
		
		return new FiberProperties(wavelength, 
				10*Math.log10(retBSC.getRealPart()[c]), 
				retIOR.getRealPart()[c], 
				10*Math.log10(retAtt.getRealPart()[c]));
	}
	
	public void addProperties(FiberProperties prop) {
		props.add(prop);
		sort();
	}
	
	
	public List<FiberProperties> getProps() {
		return props;
	}

	private void sort() {	
		Collections.sort(props, new Comparator<FiberProperties>() {
			@Override
			public int compare(FiberProperties o1, FiberProperties o2) {
				if (o1.getWavelength() < o2.getWavelength()) {
					return -1;
				}
				if (o1.getWavelength() > o2.getWavelength()) {
					return 1;
				}
				return 0;
				
			}
		});
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}
